# from icecream import ic
import json
import os
import sys

import numpy as np
import pandas as pd
import requests

from get_sql_res import gen_run_detail, gen_data_cluster
from get_response import gen_wafermap_config_mapping,gen_wafermap_config
from gen_info_dic import gen_info_dic

directory_path = os.path.dirname(os.path.abspath(__file__))
file_path=os.path.join(directory_path,'cfgs/mapping_char.json')
with open(file_path, 'r',encoding='utf8') as file:
    mapping_char = json.load(file)

def gen_Summary_one(info_dic, df_run_detail, lot_id, wafer_id):
    input_dict=info_dic['input_dict_for_mapping']
    output_dict=info_dic['output_dict_for_mapping']
    lst=[]
    for id in info_dic['input_virtual_ids']:
        # ic(id)
        tmp=df_run_detail[(df_run_detail['wafer_id']==wafer_id) & (df_run_detail['input_virtual_ids']==id)]
        # ic(tmp[['after_pass_cnt','rule_alias']])
        df = {}
        df['Lot ID'] = lot_id
        df['Wafer ID'] = wafer_id
        df['Test Stage'] = info_dic['test_stage']
        if ',' in id:
            df['Output Data Source']=mapping_char[output_dict[int(id.split(',')[0])]]
            df['Test Program']=''
            res=''
            for i in id.split(','):
                res+=input_dict[int(i)]+','
            res=res[:-1]
            df['Input Virtual DataSet']=res
            df['Output Virtual DataSet']=input_dict[int(tmp['updated_input_virtual_id'].iloc[0])]
        else:
            df['Output Data Source']=mapping_char[output_dict[int(id)]]
            df['Test Program']=''
            df['Input Virtual DataSet']=input_dict[int(id)]
            df['Output Virtual DataSet']=input_dict[int(id)]
        # Gross DIE在magconfig中取得
        df['Gross DIE']=info_dic['Gross DIE']
        # Yield_Gross Die
        if tmp['input_cnt'].iloc[0] == 0:
            df['Yield_Gross Die'] = 'NA'
        else:
            try :
                Yield_Gross_Die=tmp['pass_cnt'].iloc[0]/info_dic['Gross DIE']
                Yield_Gross_Die = f"{round(Yield_Gross_Die * 100, 2)}%"
                df['Yield_Gross Die']=Yield_Gross_Die
            except:
                df['Yield_Gross Die'] = 'NA'
        # Yield
        rs_count=tmp['triggered_count'].sum()
        if tmp['input_cnt'].iloc[0]==0:
            Yield='NA'
        else:
            try:
                Yield=tmp['pass_cnt'].iloc[0]/tmp['input_cnt'].iloc[0]
                Yield=f"{round(Yield*100,2)}%"
            except:
                Yield='NA'
        df['Yield'] =Yield
        # 新增三列
        df['Input Count'] = tmp['input_cnt'].iloc[0]
        df['Pass Count'] =tmp['pass_cnt'].fillna(0).iloc[0]
        try:
            df['Fail Count'] = df['Input Count']-df['Pass Count']
        except:
            df['Fail Count']=0
        # RS Count
        df['RS Count'] = rs_count
        # RS Rate_Gross Die
        try:
            df['RS Rate_Gross Die'] = f"{round((df['RS Count']/df['Gross DIE']*100),2)}%"
        except:
            df['RS Rate_Gross Die']='NA'
        # RS Rate
        try:
            if df['Input Count']!=0:
                df['RS Rate']=f"{round((df['RS Count']/df['Input Count']*100),2)}%"
            else:df['RS Rate']='0.0%'
        except:
            df['RS Rate']='0.0%'
        # Abnormal
        if 1 in list(tmp['abnormal']):
            df['Abnormal'] ='Y'
        else:
            df['Abnormal'] ='N'
        # 规则部分
        all_rules=info_dic['rule_map'].keys()
        dic = dict(zip(all_rules, [np.nan]*len(all_rules)))
        dic_to_add=tmp[["rule_alias", "triggered_count"]].set_index("rule_alias").to_dict(orient='dict')['triggered_count']
        dic.update(dic_to_add)
        df = {**df, **dic}
        lst.append(df)
    res_df = pd.DataFrame(lst)

    return res_df

def gen_Summary(df_run_detail, info_dic):
    lst_Summary = []
    lot_wafer_id = info_dic['lot_wafer_id']
    for lot_id in lot_wafer_id.keys():
        for wafer_id in lot_wafer_id[lot_id]:
            Summary_one = gen_Summary_one(info_dic, df_run_detail, lot_id, wafer_id)
            lst_Summary.append(Summary_one)
    # Summary_df
    Summary_df = pd.concat(lst_Summary, ignore_index=True)
    Summary_df.insert(0, 'No', range(1, len(Summary_df) + 1))
    wf_count=0
    for lot_id,wafer_id in info_dic['lot_wafer_id'].items():
        wf_count+=len(wafer_id)
    all_rules = info_dic['rule_map'].keys()
    append_row={}
    # Output Virtual DataSet
    append_row['Output Virtual DataSet'] = 'Total'
    # Gross DIE
    if info_dic['Gross DIE']=='NA':
        append_row['Gross DIE'] = 'NA'
    else:
        append_row['Gross DIE'] = info_dic['Gross DIE'] * wf_count
    # Yield_Gross Die
    try:
        Yield_Gross_Die=1-(Summary_df['RS Count'].sum()+Summary_df['Fail Count'].sum())/(info_dic['Gross DIE'] * wf_count)
        Yield_Gross_Die=f"{round(Yield_Gross_Die * 100, 2)}%"
    except:
        Yield_Gross_Die='NA'
    append_row['Yield_Gross Die']=Yield_Gross_Die
    # Yield
    Yield=(1-(Summary_df['RS Count'].sum()+Summary_df['Fail Count'].sum())/Summary_df['Input Count'].sum())
    append_row['Yield']=f"{round(Yield*100, 2)}%"
    #
    append_row['Input Count'] = Summary_df.drop_duplicates(subset='Wafer ID')['Input Count'].sum()
    append_row['Pass Count'] = Summary_df.drop_duplicates(subset='Wafer ID')['Pass Count'].sum()
    append_row['Fail Count'] =Summary_df.drop_duplicates(subset='Wafer ID')['Fail Count'].sum()
    # RS Count
    input_dict=info_dic['input_dict_for_mapping']
    last_updated_virtual_id=df_run_detail['updated_input_virtual_id'].iloc[-1]
    text=input_dict[last_updated_virtual_id]
    rs_count=Summary_df[Summary_df['Output Virtual DataSet']==text]['RS Count'].sum()
    append_row['RS Count']=rs_count
    # RS Rate_Gross Die
    try:
        rs_rate_gross_die = append_row['RS Count'] / (info_dic['Gross DIE'] * wf_count)
        append_row['RS Rate_Gross Die'] = f"{round(rs_rate_gross_die * 100, 2)}%"
    except:
        append_row['RS Rate_Gross Die'] = 'NA'
    # RS Rate
    try:
        rs_rate=append_row['RS Count']/Summary_df['Input Count'].sum()
        append_row['RS Rate'] = f"{round(rs_rate*100, 2)}%"
    except:
        append_row['RS Rate']='NA'
    # rules
    for rule in all_rules:
        append_row[rule]=Summary_df[rule].sum()
    append_row = pd.DataFrame([append_row])
    Summary_df = pd.concat([Summary_df, append_row])

    info_dic['df_info']['Summary']={
        'col_num':len(Summary_df.columns),
        'row_num':len(Summary_df)+1,
        'rs_count_loc':Summary_df.columns.get_loc('RS Count'),
        'Output_loc':Summary_df.columns.get_loc('Output Virtual DataSet')
    }
    return Summary_df

if __name__ == '__main__':
    # from icecream import ic

    with open('./cfgs/input.json', 'r') as file:
        config = json.load(file)

    rule_run_record_id = config['recordId']
    sql_info = {}
    sql_info['mysqlInfo'] = config['mysqlInfo']
    sql_info['ckInfo'] = config['ckInfo']
    sql_info['dasHost'] = config['dasHost']
    re_file_path = config['fileFullPath']

    df_run_detail = gen_run_detail(rule_run_record_id, sql_info)
    info_dic=gen_info_dic(df_run_detail, sql_info)
    ##
    # lot_id='NT41A'
    # wafer_id='NT41A_06'
    # df=gen_Summary_one(info_dic, df_run_detail, lot_id, wafer_id)
    # df.to_csv('cc.csv')
    ##
    res_df= gen_Summary(df_run_detail, info_dic)
    # res_df.to_csv('cc.csv',index=False)


